import * as dotenv from 'dotenv';
import * as path from 'path';

// 加载环境变量
dotenv.config({ path: path.resolve(process.cwd(), '.env') });

// 环境类型
export type Environment = 'development' | 'production' | 'test';

// 数据库配置接口
export interface DatabaseConfig {
  url: string;
  host: string;
  port: number;
  username: string;
  password: string;
  database: string;
}

// JWT配置接口
export interface JWTConfig {
  secret: string;
  expiresIn: string;
  refreshExpiresIn: string;
}

// 服务器配置接口
export interface ServerConfig {
  port: number;
  host: string;
  appUrl: string;
  environment: Environment;
  corsOrigin: string[];
}

// 日志配置接口
export interface LogConfig {
  level: string;
  filename: string;
  maxSize: string;
  maxFiles: string;
}

// 邮件配置接口
export interface EmailConfig {
  host: string;
  port: number;
  secure: boolean;
  auth: {
    user: string;
    pass: string;
  };
}

// 微信配置接口
export interface WeChatConfig {
  appId: string;
  appSecret: string;
  redirectUri: string;
  scope: string;
  state: string;
}

// 文件上传配置接口
export interface UploadConfig {
  maxSize: number;
  allowedTypes: string[];
  uploadPath: string;
}

// Redis配置接口
export interface RedisConfig {
  host: string;
  port: number;
  password: string | undefined;
  database: number;
  enabled: boolean;
}

// 缓存配置接口
export interface CacheConfig {
  ttl: number;
  checkPeriod: number;
  redis: RedisConfig;
}

// 主配置接口
export interface AppConfig {
  server: ServerConfig;
  database: DatabaseConfig;
  jwt: JWTConfig;
  log: LogConfig;
  email: EmailConfig;
  wechat: WeChatConfig;
  upload: UploadConfig;
  cache: CacheConfig;
}

// 验证必需的环境变量
function validateRequiredEnvVar(name: string): string {
  const value = process.env[name];
  if (!value) {
    throw new Error(`必需的环境变量 ${name} 未设置`);
  }
  return value;
}

// 解析数据库URL
function parseDatabaseUrl(url: string): DatabaseConfig {
  try {
    const urlObj = new URL(url);
    return {
      url,
      host: urlObj.hostname,
      port: parseInt(urlObj.port) || 3306,
      username: urlObj.username,
      password: urlObj.password,
      database: urlObj.pathname.slice(1),
    };
  } catch (error) {
    throw new Error(`无效的数据库URL: ${url}`);
  }
}

// 解析CORS来源
function parseCorsOrigin(origin: string): string[] {
  if (origin === '*') return ['*'];
  return origin.split(',').map(o => o.trim());
}

// 创建配置对象
export const config: AppConfig = {
  server: {
    port: parseInt(process.env['PORT'] || '3000'),
    host: process.env['HOST'] || 'localhost',
    appUrl: process.env['APP_URL'] || 'http://localhost:3000',
    environment: (process.env['NODE_ENV'] as Environment) || 'development',
    corsOrigin: parseCorsOrigin(process.env['CORS_ORIGIN'] || 'http://localhost:3000'),
  },
  
  database: parseDatabaseUrl(validateRequiredEnvVar('DATABASE_URL')),
  
  jwt: {
    secret: validateRequiredEnvVar('JWT_SECRET'),
    expiresIn: process.env['JWT_EXPIRES_IN'] || '24h',
    refreshExpiresIn: process.env['JWT_REFRESH_EXPIRES_IN'] || '7d',
  },
  
  log: {
    level: process.env['LOG_LEVEL'] || 'info',
    filename: process.env['LOG_FILENAME'] || 'logs/app.log',
    maxSize: process.env['LOG_MAX_SIZE'] || '20m',
    maxFiles: process.env['LOG_MAX_FILES'] || '14d',
  },
  
  email: {
    host: process.env['EMAIL_HOST'] || 'smtp.gmail.com',
    port: parseInt(process.env['EMAIL_PORT'] || '587'),
    secure: process.env['EMAIL_SECURE'] === 'true',
    auth: {
      user: process.env['EMAIL_USER'] || '',
      pass: process.env['EMAIL_PASS'] || '',
    },
  },
  
  wechat: {
    appId: process.env['WECHAT_APP_ID'] || '',
    appSecret: process.env['WECHAT_APP_SECRET'] || '',
    redirectUri: process.env['WECHAT_REDIRECT_URI'] || 'http://localhost:3000/api/client/auth/wechat/callback',
    scope: process.env['WECHAT_SCOPE'] || 'snsapi_userinfo',
    state: process.env['WECHAT_STATE'] || 'wechat_login',
  },
  
  upload: {
    maxSize: parseInt(process.env['UPLOAD_MAX_SIZE'] || '5242880'), // 5MB
    allowedTypes: (process.env['UPLOAD_ALLOWED_TYPES'] || 'jpg,jpeg,png,gif,pdf,doc,docx').split(','),
    uploadPath: process.env['UPLOAD_PATH'] || 'uploads',
  },
  
  cache: {
    ttl: parseInt(process.env['CACHE_TTL'] || '3600'), // 1小时
    checkPeriod: parseInt(process.env['CACHE_CHECK_PERIOD'] || '600'), // 10分钟
    redis: {
      host: process.env['REDIS_HOST'] || 'localhost',
      port: parseInt(process.env['REDIS_PORT'] || '6379'),
      password: process.env['REDIS_PASSWORD'] || undefined,
      database: parseInt(process.env['REDIS_DB'] || '0'),
      enabled: process.env['REDIS_ENABLED'] !== 'false',
    },
  },
};

// 验证配置
export function validateConfig(): void {
  // 验证JWT密钥长度
  if (config.jwt.secret.length < 32) {
    throw new Error('JWT_SECRET 必须至少32个字符长');
  }
  
  // 验证端口范围
  if (config.server.port < 1 || config.server.port > 65535) {
    throw new Error('PORT 必须在1-65535范围内');
  }
  
  // 验证环境类型
  if (!['development', 'production', 'test'].includes(config.server.environment)) {
    throw new Error('NODE_ENV 必须是 development、production 或 test');
  }
  
  // 验证数据库配置
  if (!config.database.host || !config.database.database) {
    throw new Error('数据库配置无效');
  }
  
  // 验证Redis配置
  if (config.cache.redis.enabled) {
    if (!config.cache.redis.host || config.cache.redis.port < 1 || config.cache.redis.port > 65535) {
      throw new Error('Redis配置无效');
    }
  }
}

// 获取环境特定的配置
export function getEnvironmentConfig(): Partial<AppConfig> {
  switch (config.server.environment) {
    case 'development':
      return {
        log: {
          ...config.log,
          level: 'debug',
        },
        cache: {
          ...config.cache,
          ttl: 300, // 开发环境缓存5分钟
          redis: {
            ...config.cache.redis,
            enabled: true, // 开发环境启用Redis
          },
        },
      };
      
    case 'production':
      return {
        log: {
          ...config.log,
          level: 'warn',
        },
        server: {
          ...config.server,
          corsOrigin: config.server.corsOrigin.filter(origin => origin !== '*'),
        },
      };
      
    case 'test':
      return {
        log: {
          ...config.log,
          level: 'error',
        },
        cache: {
          ...config.cache,
          ttl: 60, // 测试环境缓存1分钟
          redis: {
            ...config.cache.redis,
            enabled: false, // 测试环境禁用Redis
          },
        },
      };
      
    default:
      return {};
  }
}

// 初始化配置
export function initializeConfig(): AppConfig {
  try {
    validateConfig();
    const envConfig = getEnvironmentConfig();
    return { ...config, ...envConfig };
  } catch (error) {
    console.error('配置初始化失败:', error);
    process.exit(1);
  }
}

// 导出配置工具类
export { ConfigUtils, ConfigValidator } from './utils';

// 导出默认配置
export default config; 